import time
import ssd1306
from machine import I2C, Pin

# draw an image from buf
def drawImage(rows, cols, buf, offset_col, offset_row):
	buf_index = 0 
	for y in range(rows):
		Y = y + offset_row
		BUF_index = 128*Y + offset_col
		if BUF_index > 1023:
			return
		for x in range(cols):
			display.buffer[BUF_index + x] = buf[buf_index]
			buf_index += 1

# draw a picture from a img file
def drawImageFile(imgFile,offset_col, offset_row):
	try:
		f = open(imgFile,'rb')
		data = f.read(1)
		rows=int.from_bytes(data, "big")
		data = f.read(1)
		cols=int.from_bytes(data, "big")
		buf=f.read(rows*cols)
		f.close()
		drawImage(rows,cols,buf,offset_col, offset_row)
		del(buf)
	except OSError as er:
		print(er)

# display
i2c = I2C(scl=Pin(2), sda=Pin(14)) # D4 D5
display = ssd1306.SSD1306_I2C(128, 64, i2c)
# flip screen
display.write_cmd(0xA0) # SEGREMAP
display.write_cmd(0xC0) # COMSCANINC

while True:
    for i in range(1,4):
        display.fill(0)
        drawImageFile("img/0"+str(i)+".pb",0,0)
        display.show()
        time.sleep(1)